package com.tiancheng.trade.merchant.configuration;


import com.tiancheng.trade.merchant.enums.MerchantQueueEnum;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.EnableRabbit;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author jiangjun
 * @description 消息队列相关配置
 * @date 2024/10/14 23:43
 */
@EnableRabbit
@Configuration
public class RabbitMqConfig {

    /**
     * 订单消息实际消费队列所绑定的交换机
     */
    @Bean
    DirectExchange merchantDirect() {
        return (DirectExchange) ExchangeBuilder
                .directExchange(MerchantQueueEnum.QUEUE_MERCHANT_REGISTER.getExchange())
                .durable(true)
                .build();
    }

    /**
     * 订单延迟队列队列所绑定的交换机
     */
    @Bean
    DirectExchange merchantTtlDirect() {
        return (DirectExchange) ExchangeBuilder
                .directExchange(MerchantQueueEnum.QUEUE_TTL_MERCHANT_REGISTER_CANCEL.getExchange())
                .durable(true)
                .build();
    }

    /**
     * 订单实际消费队列
     */
    @Bean
    public Queue orderQueue() {
        return new Queue(MerchantQueueEnum.QUEUE_MERCHANT_REGISTER.getName());
    }

    /**
     * 订单延迟队列（死信队列）
     */
    @Bean
    public Queue orderTtlQueue() {
        return QueueBuilder
                .durable(MerchantQueueEnum.QUEUE_TTL_MERCHANT_REGISTER_CANCEL.getName())
                .withArgument("x-dead-letter-exchange", MerchantQueueEnum.QUEUE_MERCHANT_REGISTER.getExchange())//到期后转发的交换机
                .withArgument("x-dead-letter-routing-key", MerchantQueueEnum.QUEUE_MERCHANT_REGISTER.getRouteKey())//到期后转发的路由键
                .build();
    }

    /**
     * 将订单队列绑定到交换机
     */
    @Bean
    Binding orderBinding(DirectExchange merchantDirect, Queue orderQueue){
        return BindingBuilder
                .bind(orderQueue)
                .to(merchantDirect)
                .with(MerchantQueueEnum.QUEUE_MERCHANT_REGISTER.getRouteKey());
    }

    /**
     * 将商户注册延迟队列绑定到交换机
     */
    @Bean
    Binding orderTtlBinding(DirectExchange merchantTtlDirect,Queue orderTtlQueue){
        return BindingBuilder
                .bind(orderTtlQueue)
                .to(merchantTtlDirect)
                .with(MerchantQueueEnum.QUEUE_TTL_MERCHANT_REGISTER_CANCEL.getRouteKey());
    }
}
